<script setup>
import {ref, computed, onMounted, watch} from 'vue'
import { useAppStore } from "../store/stroes.js"
import { ElTooltip } from 'element-plus'

const appStore = useAppStore()
const currentIndex = ref(0)
const isLoading = ref(true)
const isPlaying = ref(false)
let stopLoop = false; // 控制循环的外部变量
// 监听数据加载
watch(() => appStore.sentenceData, (newData) => {
  if (newData && newData.length > 0) {
    const today = new Date()
    const index = today.getDate() % newData.length
    currentIndex.value = index
    isLoading.value = false
  }
}, { immediate: true })


// 根据日期设置初始索引
onMounted(() => {
  const today = new Date()
  const index = today.getDate() % appStore.sentenceData.length
  currentIndex.value = index
})

// 当前谚语
const currentSentence = computed(() => appStore.sentenceData[currentIndex.value])

// 切换上一条
const prevSentence = () => {
  currentIndex.value = (currentIndex.value - 1 + appStore.sentenceData.length) % appStore.sentenceData.length
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 切换下一条
const nextSentence = () => {
  currentIndex.value = (currentIndex.value + 1) % appStore.sentenceData.length
}
// 播放音频（返回 Promise）
function playAudio() {
  return new Promise((resolve, reject) => {
    if (!currentSentence.value?.sentence) {
      resolve();
      return;
    }

    // 生成音频路径
    const sentenceName = currentSentence.value.sentence;
    const audioPath = `/audio/谚语audio/${sentenceName}.wav`;

    const audio = new Audio(audioPath);

    // 播放结束时 resolve
    audio.onended = () => {
      resolve();
    };

    // 播放出错时也 resolve（避免死循环）
    audio.onerror = (err) => {
      console.error('音频播放失败:', err);
      resolve();
    };

    // 播放
    audio.play().catch(err => {
      console.error('音频播放失败:', err);
      resolve();
    });
  });
}

const autoaudio = async (stop) => {
  isPlaying.value = !isPlaying.value;

  if (isPlaying.value) {
    stopLoop = false;
    while (!stopLoop) {
      await playAudio();   // ✅ 等待播放结束
      nextSentence();      // ✅ 切换下一句
      await sleep(stop);   // ✅ 间隔等待
    }
  } else {
    stopLoop = true;
  }
};

</script>

<template>
  <el-row justify="center" align="top" class="sentence-container">
    <el-col :span="24">

      <!-- 数据加载中显示占位 -->
      <div v-if="isLoading" class="loading-text">
        加载中...
      </div>

      <!-- 数据加载完成显示谚语 -->
      <div v-else>
        <el-row class="sentence-box" style="margin-top:5px; text-align: center;">
          <el-tooltip :content="currentSentence?.reading || ''" placement="right" popper-class="custom-tooltip">
            <div style="font-size: 20px; font-weight: bold;">
              {{ currentSentence?.sentence || '' }}
            </div>
          </el-tooltip>
          <div style="font-size: 18px; color: #555; margin-top: 10px;margin-left: 10px">
            {{ currentSentence?.translation || '' }}
          </div>
        </el-row>

        <!-- 底部按钮 -->
        <div class="btn-group" >
          <el-button size="small" @click="prevSentence">上一条</el-button>
          <span style="font-size: 12px;margin-left: 10px;margin-right: 10px">
            {{ currentIndex + 1 }} / {{ appStore.sentenceData.length }}
          </span>
          <el-button size="small" @click="nextSentence">下一条</el-button>
          <el-button size="small" @click="playAudio">音频</el-button>
          <el-button size="small" @click="autoaudio(500)">
            {{ isPlaying ? '停止自动播放' : '自动播放' }}
          </el-button>
        </div>
      </div>

    </el-col>
  </el-row>
</template>

<style>
.sentence-container {
  width: 100%;
}
.custom-tooltip {
  background-color: #ffffff !important;
  color: #000000 !important;
  font-size: 16px !important;

  border-radius: 4px !important;

}

.sentence-box {

  border-radius: 8px;
  transition: all 0.1s;
}


</style>
